package org.javacore.base.copy;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.io.Serializable;

/**
 * Created by Administrator on 2017/2/14.
 */
class People implements Serializable{
    private static final long serialVersionUID = 157293742277901776L;
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}
class Worker implements Serializable{

    private static final long serialVersionUID = -3998995503617120783L;
    private String name;
    private People people;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public People getPeople() {
        return people;
    }

    public void setPeople(People people) {
        this.people = people;
    }

    public Object deepClone() throws IOException, OptionalDataException,
        ClassNotFoundException {
        // 将对象写到流里
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        oo.writeObject(this);
        // 从流里读出来
        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi = new ObjectInputStream(bi);
        return (oi.readObject());
    }

}

public class DeepCopy2 {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        People p = new People();
        p.setName("Tom Family");
        Worker t = new Worker();
        t.setName("Tom");
        t.setPeople(p);
        Worker worker = (Worker) t.deepClone();
        worker.setName("Tom2");
        worker.getPeople().setName("Tom2 Family");
        System.out.println(t.getName()+" "+ t.getPeople().getName());
        System.out.println(worker.getName()+" "+ worker.getPeople().getName());
    }
}
